const User = require('../models/user');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { JWT_SECRET } = require('../middleware/auth');

class UserController {
    // 创建用户
    static async create(ctx) {
        try {
            const { name, age, email, password } = ctx.request.body;

            // 检查用户名是否存在
            const existingName = await User.findOne({ where: { name } });
            if (existingName) {
                ctx.status = 400;
                ctx.body = {
                    code: 400,
                    errMsg: '用户名已存在'
                };
                return;
            }

            // 检查邮箱是否存在
            const existingEmail = await User.findOne({ where: { email } });
            if (existingEmail) {
                ctx.status = 400;
                ctx.body = {
                    code: 400,
                    errMsg: '邮箱已被注册'
                };
                return;
            }

            const user = await User.create({
                name,
                age,
                email,
                password
            });

            const token = jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '1h' });

            ctx.body = {
                code: 200,
                data: {
                    user: {
                        id: user.id,
                        name: user.name,
                        age: user.age,
                        email: user.email
                    },
                    token
                }
            };
        } catch (error) {
            ctx.status = 400;
            // 检查是否是邮箱验证错误
            if (error.name === 'SequelizeValidationError') {
                const validationErrors = error.errors;
                for (let err of validationErrors) {
                    if (err.path === 'email') {
                        ctx.body = {
                            code: 400,
                            errMsg: '邮箱格式不正确'
                        };
                        return;
                    }
                }
            }
            // 其他错误
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }

    // 用户登录
    static async login(ctx) {
        try {
            const { email, password } = ctx.request.body;
            
            const user = await User.findOne({ where: { email } });
            if (!user) {
                ctx.status = 400;
                ctx.body = {
                    code: 400,
                    errMsg: '用户不存在'
                };
                return;
            }

            const isValidPassword = await bcrypt.compare(password, user.password);
            if (!isValidPassword) {
                ctx.status = 400;
                ctx.body = {
                    code: 400,
                    errMsg: '密码错误'
                };
                return;
            }

            const token = jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '1h' });

            ctx.body = {
                code: 200,
                data: {
                    user: {
                        id: user.id,
                        name: user.name,
                        age: user.age,
                        email: user.email
                    },
                    token
                }
            };
        } catch (error) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }

    // 获取所有用户
    static async getAll(ctx) {
        try {
            const users = await User.findAll({
                attributes: ['id', 'name', 'age', 'email']
            });
            ctx.body = {
                code: 200,
                data: users
            };
        } catch (error) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }

    // 获取单个用户
    static async getOne(ctx) {
        try {
            const user = await User.findByPk(ctx.params.id, {
                attributes: ['id', 'name', 'age', 'email']
            });
            if (!user) {
                ctx.status = 404;
                ctx.body = {
                    code: 404,
                    errMsg: '用户不存在'
                };
                return;
            }
            ctx.body = {
                code: 200,
                data: user
            };
        } catch (error) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }

    // 更新用户
    static async update(ctx) {
        try {
            const user = await User.findByPk(ctx.params.id);
            if (!user) {
                ctx.status = 404;
                ctx.body = {
                    code: 404,
                    errMsg: '用户不存在'
                };
                return;
            }

            const { name, age, email } = ctx.request.body;

            await user.update({
                name,
                age,
                email
            });

            ctx.body = {
                code: 200,
                data: {
                    id: user.id,
                    name: user.name,
                    age: user.age,
                    email: user.email
                }
            };
        } catch (error) {
            ctx.status = 400;
            // 检查是否是邮箱验证错误
            if (error.name === 'SequelizeValidationError') {
                const validationErrors = error.errors;
                for (let err of validationErrors) {
                    if (err.path === 'email') {
                        ctx.body = {
                            code: 400,
                            errMsg: '邮箱格式不正确'
                        };
                        return;
                    }
                }
            }
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }

    // 删除用户
    static async delete(ctx) {
        try {
            const user = await User.findByPk(ctx.params.id);
            if (!user) {
                ctx.status = 404;
                ctx.body = {
                    code: 404,
                    errMsg: '用户不存在'
                };
                return;
            }

            await user.destroy();
            ctx.body = {
                code: 200,
                data: {
                    message: '用户已删除'
                }
            };
        } catch (error) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                errMsg: error.message
            };
        }
    }
}

module.exports = UserController; 